import Vue from "vue";
import VueRouter from "vue-router";
Vue.use(VueRouter);

let router= new VueRouter({
	routes:[],
	mode:"history"
	
});
import axios from"./axios.js"

import home from"../pages/home.vue";
import follow from"../pages/follow.vue";
import detail from"../pages/detail.vue";
import login from"../pages/login.vue";
import coulumn from"../pages/coulumn.vue";
import reg from"../pages/reg.vue";
import user from"../pages/user.vue";
import nopage from"../pages/no-page.vue";
import scj from"../pages/scj.vue";




let data =[{path:"/home",component:home},
           {path:"/follow",component:follow},
		   {path:"/detail/:_id",component:detail},
		   {path:"/login",component:login},
		    {path:"/coulumn",component:coulumn},
			{path:"/reg",component:reg},
			{path:"/user",component:user},
			{path:"/scj",component:scj},
			{path:"/",redirect:"/home"},//重新按照/home走路由
			{path:"*",component:nopage}
];

// 路由配置 ，路由要先经过beforeeact才能通过
// 一定是先经过beforeEach才会再通过路由
router.addRoutes(data)

router.beforeEach((to,from,next)=>{
	
	let collectionName="";
	let path= to.path;
	if(path.includes("./login")||path.includes("./reg")){
		next()
	}else{if(/home/.test(path)){collectionName="home"}
	if(/follow/.test(path)){collectionName="follow"}
	if(/login/.test(path)){collectionName="login"}
	if(/detail/.test(path)){collectionName=to.query.collectionName}
	if(/coulumn/.test(path)){collectionName="coulumn"}
	if(/reg/.test(path)){collectionName="reg"}
	if(/user/.test(path)){collectionName="user"}
	if(/scj/.test(path)){collectionName="scj"}
	 
	 let url = to.params._id ?  `/api/news/${collectionName}/${to.params._id}`:`/api/news/${collectionName}`;
	// let url =`/api/news/${collectionName}`;
	    url = collectionName ==="user"? `/api/${collectionName}`:url;
	if(collectionName){
		axios.get(url).then(
		res=>{
			if(res.data.err === 2 && !to.path.includes("/login")){
				next(`/login?${to.fullPath}`)
			}else{
				to.query.data =res.data.data;
				next()
			}
		}
	)
	}else{
		next()
	}
	}	
})

export default router;